package com.muyu.system.service.impl;

import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.DanmoAddresses;
import com.muyu.common.core.enums.OrderStatus;
import com.muyu.common.core.enums.PayMethod;
import com.muyu.system.domain.*;
import com.muyu.system.mapper.*;
import com.muyu.system.req.CartItemDto;
import com.muyu.system.req.DanmoShoppingCartOrdersDto;
import com.muyu.system.req.DanmoShoppingOrdersReq;
import com.muyu.system.req.ShoppingCartDto;
import com.muyu.system.service.IDanmoShoppingOrderDetailsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 订单详情Service业务层处理
 *
 * @author yangle
 * @date 2024-09-29
 */
@Service
public class DanmoShoppingOrderDetailsServiceImpl implements IDanmoShoppingOrderDetailsService {
    @Autowired
    private DanmoShoppingOrderDetailsMapper danmoShoppingOrderDetailsMapper;

    @Autowired
    private DanmoMarketOrderMapper danmoMarketOrderMapper;

    @Autowired
    private DanmoShoppingProductsMapper danmoShoppingProductsMapper;

    @Autowired
    private DanmoShoppingSpecificationMapper danmoShoppingSpecificationMapper;

    @Autowired
    private DanmoShoppingCartMapper danmoShoppingCartMapper;

    @Autowired
    private DanmoShoppingOrderCartDetailsMapper danmoShoppingOrderCartDetailsMapper;


    /**
     * 查询订单详情
     *
     * @param id 订单详情主键
     * @return 订单详情
     */
    @Override
    public DanmoShoppingOrdersReq selectDanmoShoppingOrderDetailsById(Long id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //        1.根据订单id查询出该订单
        DanmoShoppingOrderDetails danmoShoppingOrderDetails = danmoShoppingOrderDetailsMapper.selectDanmoShoppingOrderDetailsById(id);
        if (danmoShoppingOrderDetails == null) {
            return null;
        }
        List<DanmoShoppingProducts> danmoShoppingProductsList = new ArrayList<>();
        if (danmoShoppingOrderDetails.getIsShoppingCart() != null && danmoShoppingOrderDetails.getIsShoppingCart().equals("true")) {
            List<DanmoShoppingOrderCartDetails> danmoShoppingOrderCartDetails = danmoShoppingOrderCartDetailsMapper.selectDanmoShoppingOrderCartDetailsByProductId(danmoShoppingOrderDetails.getId());
            Long[] productIds = danmoShoppingOrderCartDetails.stream()
                    .map(danmoShoppingOrderCartDetail -> danmoShoppingOrderCartDetail.getProductId())
                    .toArray(Long[]::new);
            danmoShoppingProductsList = danmoShoppingProductsMapper.selectDanmoShoppingProductsByIds(productIds);
        }else {
            Long productId = danmoShoppingOrderDetails.getProductId();
            DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsByOrderInProductId(productId);
            DanmoShoppingSpecification danmoShoppingSpecification = danmoShoppingSpecificationMapper.selectDanmoShoppingSpecificationByIdAndProductSpecifications(productId, danmoShoppingOrderDetails.getProductSpecifications());
            danmoShoppingProducts.setSkuName(danmoShoppingSpecification.getName());
            danmoShoppingProductsList.add(danmoShoppingProducts);
        }


        Long addressesId = danmoShoppingOrderDetails.getAddressesId();
        DanmoAddresses danmoAddresses = danmoShoppingSpecificationMapper.selectDanmoAddressByAddressIdAndUserId(addressesId, loginUser.getUserid());

//        2.判断出该订单所绑定的用户id是否为当前用户
        if (danmoShoppingOrderDetails.getUserId().equals(loginUser.getUserid())) {
            DanmoShoppingOrdersReq danmoShoppingOrdersReq = new DanmoShoppingOrdersReq();
            danmoShoppingOrdersReq.setDanmoAddresses(danmoAddresses);
            danmoShoppingOrdersReq.setDanmoShoppingProductsList(danmoShoppingProductsList);
            danmoShoppingOrdersReq.setDanmoShoppingOrderDetails(danmoShoppingOrderDetails);
            return danmoShoppingOrdersReq;
        }
        return null;
    }

    /**
     * 查询订单详情列表
     *
     * @param danmoShoppingOrderDetails 订单详情
     * @return 订单详情
     */
    @Override
    public List<DanmoShoppingOrderDetails> selectDanmoShoppingOrderDetailsList(DanmoShoppingOrderDetails danmoShoppingOrderDetails) {
        return danmoShoppingOrderDetailsMapper.selectDanmoShoppingOrderDetailsList(danmoShoppingOrderDetails);
    }

    /**
     * 新增订单详情
     *
     * @param danmoShoppingOrderDetails 订单详情
     * @return 结果
     */
    @Override
    public int insertDanmoShoppingOrderDetails(DanmoShoppingOrderDetails danmoShoppingOrderDetails) {
        danmoShoppingOrderDetails.setCreateTime(DateUtils.getNowDate());
        return danmoShoppingOrderDetailsMapper.insertDanmoShoppingOrderDetails(danmoShoppingOrderDetails);
    }

    /**
     * 支付成功
     *
     * @param danmoShoppingOrdersReq 订单详情
     * @return
     */
    @Override
    @Transactional
    public Result updateDanmoShoppingOrderDetails(DanmoShoppingOrdersReq danmoShoppingOrdersReq) {
        Long orderId = danmoShoppingOrdersReq.getOrderId();

        DanmoShoppingOrderDetails danmoShoppingOrderDetails = danmoShoppingOrderDetailsMapper.selectDanmoShoppingOrderDetailsById(orderId);
        if (danmoShoppingOrderDetails == null) {
            return Result.error("订单详情未找到");
        }

        DanmoMarketOrder danmoMarketOrder = danmoMarketOrderMapper.selectSingleOrder(orderId);
        if (danmoMarketOrder == null) {
            return Result.error("市场订单未找到");
        }

        if (danmoShoppingOrderDetails.getOrderStatus() != 1 || danmoMarketOrder.getOrderStatus() != OrderStatus.PAY_PENDING) {
            return Result.error("订单状态异常，请重试");
        }

        // 更新支付信息
        updateOrderDetails(danmoShoppingOrderDetails, danmoShoppingOrdersReq.getPaymentMethod());
        updateMarketOrder(danmoMarketOrder, danmoShoppingOrdersReq.getPaymentMethod());

        // 保存更新
        danmoShoppingOrderDetailsMapper.updateDanmoShoppingOrderDetails(danmoShoppingOrderDetails);
        danmoMarketOrderMapper.updateDanmoMarketOrder(danmoMarketOrder);

        return Result.success(1, "支付成功");
    }

    private void updateOrderDetails(DanmoShoppingOrderDetails orderDetails, Long paymentMethod) {
        orderDetails.setPaymentTime(DateUtils.getNowDate());
        orderDetails.setPaymentMethod(paymentMethod);
        orderDetails.setOrderStatus(2L); // 使用常量
    }

    private void updateMarketOrder(DanmoMarketOrder marketOrder, Long paymentMethod) {
        marketOrder.setPaymentTime(DateUtils.getNowDate());
        marketOrder.setPaymentMethod(PayMethod.getPayChannel(paymentMethod.intValue()));
        marketOrder.setOrderStatus(OrderStatus.TO_BE_SHIPPED); // 使用常量
    }

    /**
     * 批量删除订单详情
     *
     * @param ids 需要删除的订单详情主键
     * @return 结果
     */
    @Override
    public int deleteDanmoShoppingOrderDetailsByIds(Long[] ids) {
        return danmoShoppingOrderDetailsMapper.deleteDanmoShoppingOrderDetailsByIds(ids);
    }

    /**
     * 删除订单详情信息
     *
     * @param id 订单详情主键
     * @return 结果
     */
    @Override
    public int deleteDanmoShoppingOrderDetailsById(Long id) {
        return danmoShoppingOrderDetailsMapper.deleteDanmoShoppingOrderDetailsById(id);
    }


    /**
     * 直接购买商品生成订单
     *
     * @param danmoShoppingOrdersReq
     * @return
     */
    @Override
    public Result addShoppingOrder(DanmoShoppingOrdersReq danmoShoppingOrdersReq) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
//         获取用户地址列表
//        DanmoAddresses danmoMarketOrder = new DanmoAddresses();
//        danmoMarketOrder.setUserId(loginUser.getUserid());
        DanmoAddresses danmoAddresses = null;
        if (danmoShoppingOrdersReq.getShippingAddress() == null) {
            DanmoAddresses defaultAddress = danmoShoppingOrderDetailsMapper.selectByAddress(loginUser.getUserid());
            if (defaultAddress == null) {
                return Result.error("请先勾选默认地址");
            }
            danmoAddresses = danmoShoppingOrderDetailsMapper.selectByAddress(loginUser.getUserid());
        } else {
            DanmoAddresses address = danmoShoppingOrderDetailsMapper.selectDanmoAddressesById(danmoShoppingOrdersReq.getShippingAddress());
            if (address == null) {
                return Result.error("订单创建失败，请重试");
            }
            danmoAddresses = address;
        }

        // 生成订单ID
        Long id = generateOrderId();

        // 订单总金额
        BigDecimal sum = null;
        BigDecimal price = danmoShoppingOrdersReq.getPrice();
        Long quantity = danmoShoppingOrdersReq.getQuantity();
        sum = price.multiply(new BigDecimal(quantity));

        // 创建订单对象
        DanmoMarketOrder danmoMarketOrder1 = DanmoMarketOrder.builder()
                .id(id)
                .orderStatus(OrderStatus.PAY_PENDING)
                .orderTime(DateUtils.getNowDate())
                .totalAmount(sum)
                .userId(loginUser.getUserid())
                .productId(danmoShoppingOrdersReq.getId())
                .addressesId(danmoAddresses.getId())
                .createBy(loginUser.getUsername())
                .createTime(DateUtils.getNowDate())
                .updateBy(loginUser.getUsername())
                .updateTime(DateUtils.getNowDate())
                .remark(danmoShoppingOrdersReq.getRemark())
                .paymentMethod(PayMethod.getPayChannel(danmoShoppingOrdersReq.getPaymentMethod().intValue()))
                .orderSource(2L)
                .quantity(danmoShoppingOrdersReq.getQuantity())
                .build();

        DanmoShoppingOrderDetails danmoMarketOrderDetails = DanmoShoppingOrderDetails.builder()
                .id(id)
                .userId(loginUser.getUserid())
                .quantity(danmoShoppingOrdersReq.getQuantity())
                .orderStatus(1L)
                .productId(danmoShoppingOrdersReq.getId())
                .productSpecifications(danmoShoppingOrdersReq.getProductSpecifications())
                .orderTime(DateUtils.getNowDate())
                .totalAmount(sum)
                .unitPrice(danmoShoppingOrdersReq.getPrice())
                .addressesId(danmoAddresses.getId())
                .paymentMethod(danmoShoppingOrdersReq.getPaymentMethod())
                .build();
        // 插入订单并返回结果
        try {
            int insertResult = danmoMarketOrderMapper.insertDanmoMarketOrder(danmoMarketOrder1);
            int i = danmoShoppingOrderDetailsMapper.insertDanmoShoppingOrderDetails(danmoMarketOrderDetails);
            if (insertResult > 0 && i > 0) {
                DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsById(danmoShoppingOrdersReq.getId());
                danmoShoppingProducts.setId(danmoShoppingOrdersReq.getId());
                danmoShoppingProducts.setStock(danmoShoppingProducts.getStock() - danmoShoppingOrdersReq.getQuantity());
                danmoShoppingProducts.setSales(danmoShoppingProducts.getSales() + danmoShoppingOrdersReq.getQuantity());
                danmoShoppingProductsMapper.updateDanmoShoppingProducts(danmoShoppingProducts);
                String orderId = String.valueOf(id);
                return Result.success(orderId, "订单创建成功");
            } else {
                return Result.error("订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("订单创建失败: " + e.getMessage());
        }
    }

    /**
     * 购物车订单展示
     *
     * @param shoppingCartDto
     * @return
     */
    @Override
    public Result selectDanmoShoppingCart(ShoppingCartDto shoppingCartDto) {
//        总价
        DanmoShoppingCartOrdersDto danmoShoppingCartOrdersDto = new DanmoShoppingCartOrdersDto();
        danmoShoppingCartOrdersDto.setFreightSum(BigDecimal.valueOf(0));
        danmoShoppingCartOrdersDto.setPriceSum(BigDecimal.valueOf(0));
        for (CartItemDto danmoShoppingCartList : shoppingCartDto.getDanmoShoppingCartLists()) {
            for (DanmoShoppingCartList shoppingCartList : danmoShoppingCartList.getDanmoShoppingCartLists()) {
                if (shoppingCartList.getChecked()) {
                    DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsById(shoppingCartList.getProductId());
                    if (danmoShoppingProducts.getStock() < shoppingCartList.getQuantity()) {
                        return Result.error(1, "库存不足");
                    }
                    if (!danmoShoppingProducts.getPosExpress().equals("包邮")) {
                        danmoShoppingCartOrdersDto.setFreightSum(danmoShoppingCartOrdersDto.getFreightSum().add(danmoShoppingProducts.getFreight()));
                    }
                }
            }
        }
//        将购物车对象放入到购物车订单对象中
        danmoShoppingCartOrdersDto.setShoppingCartDto(shoppingCartDto);
        danmoShoppingCartOrdersDto.setPriceSum(shoppingCartDto.getTotalPrice().add(danmoShoppingCartOrdersDto.getFreightSum()));

        LoginUser loginUser = SecurityUtils.getLoginUser();

        DanmoAddresses danmoAddresses = danmoShoppingSpecificationMapper.selectDanmoDefaultAddress(loginUser.getUserid());
        if (danmoAddresses == null) {
            DanmoAddresses danmoAddressesFirst = danmoShoppingSpecificationMapper.selectDanmoDefaultAddressFirst(loginUser.getUserid());
            if (danmoAddressesFirst == null) {
                return Result.error("请选择地址");
            }
            danmoShoppingCartOrdersDto.setDanmoAddresses(danmoAddressesFirst);
        } else {
            danmoAddresses.setPhone(generateOrderNumber(danmoAddresses.getPhone()));
            danmoShoppingCartOrdersDto.setDanmoAddresses(danmoAddresses);
        }
        return Result.success(danmoShoppingCartOrdersDto);
    }

    /**
     * 通过购物车生成订单
     *
     * @param danmoShoppingCartOrdersDto
     * @return
     */
    @Override
    public Result addSHoppingOrderByShoppingCart(DanmoShoppingCartOrdersDto danmoShoppingCartOrdersDto) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 从购物车订单 DTO 中获取购物车列表
        List<CartItemDto> danmoShoppingCartLists = danmoShoppingCartOrdersDto.getShoppingCartDto().getDanmoShoppingCartLists();

        // 遍历购物车列表，处理每个旗舰店的订单
        for (CartItemDto danmoShoppingCartList : danmoShoppingCartLists) {
            // 创建一个新的订单详情对象
            DanmoShoppingOrderDetails danmoShoppingOrderDetails = createOrderDetails(loginUser);

            // 处理该购物车中的所有商品
            processShoppingCartItems(danmoShoppingCartList, danmoShoppingOrderDetails, loginUser);

            // 如果购物车中有商品被选中，则插入订单详情
            if (danmoShoppingOrderDetails.getIsShoppingCart()) {
                finalizeOrder(danmoShoppingOrderDetails, danmoShoppingCartOrdersDto, loginUser);
            }
        }

        // 返回成功信息
        return Result.success(1, "订单生成成功");
    }



    /**
     * 创建一个新的订单详情对象
     */
    private DanmoShoppingOrderDetails createOrderDetails(LoginUser loginUser) {
        DanmoShoppingOrderDetails orderDetails = new DanmoShoppingOrderDetails();
        // 初始化数量为 0
        orderDetails.setQuantity(0L);
        // 初始化总金额为 0
        orderDetails.setTotalAmount(BigDecimal.ZERO);
        // 生成订单 ID
        orderDetails.setId(generateOrderId());
        orderDetails.setCreateBy(String.valueOf(loginUser.getUserid()));
        orderDetails.setCreateTime(DateUtils.getNowDate());
        return orderDetails;
    }

    /**
     * 处理购物车中的商品
     */
    private void processShoppingCartItems(CartItemDto danmoShoppingCartList, DanmoShoppingOrderDetails orderDetails, LoginUser loginUser) {
        // 遍历每个购物车中的商品
        for (DanmoShoppingCartList shoppingCartList : danmoShoppingCartList.getDanmoShoppingCartLists()) {
            // 如果商品被选中
            if (shoppingCartList.getChecked()) {
                // 标记订单为来自购物车
                orderDetails.setIsShoppingCart(true);
                // 创建购物车订单详情
                createOrderCartDetail(shoppingCartList, orderDetails, loginUser);
                // 删除已处理的购物车项
                danmoShoppingCartMapper.deleteDanmoShoppingCartById(shoppingCartList.getId());
            }
        }
    }

    /**
     * 创建一个订单购物车详情并更新订单详情中的信息
     */
    private void createOrderCartDetail(DanmoShoppingCartList shoppingCartList, DanmoShoppingOrderDetails orderDetails, LoginUser loginUser) {
        DanmoShoppingOrderCartDetails orderCartDetails = new DanmoShoppingOrderCartDetails();
        // 设置订单 ID
        orderCartDetails.setShoppingOrderId(orderDetails.getId());
        // 设置商品 ID
        orderCartDetails.setProductId(shoppingCartList.getProductId());
        // 设置商品规格
        orderCartDetails.setProductSpecifications(shoppingCartList.getShoppingSkuId());
        // 设置购买数量
        orderCartDetails.setQuantity(shoppingCartList.getQuantity());
        // 设置单价
        orderCartDetails.setUnitPrice(shoppingCartList.getPrice());
        // 设置用户 ID
        orderCartDetails.setUserId(loginUser.getUserid());

        // 插入订单购物车详情
        danmoShoppingOrderCartDetailsMapper.insertDanmoShoppingOrderCartDetails(orderCartDetails);

        // 更新订单详情的数量和总金额
        orderDetails.setQuantity(orderDetails.getQuantity() + shoppingCartList.getQuantity());
        orderDetails.setTotalAmount(orderDetails.getTotalAmount().add(shoppingCartList.getPrice().multiply(BigDecimal.valueOf(shoppingCartList.getQuantity()))));

        // 如果商品不包邮，则更新运费
        if (shoppingCartList.getPoxExpress() != null && !"包邮".equals(shoppingCartList.getPoxExpress())) {
            // 更新总金额
            orderDetails.setTotalAmount(orderDetails.getTotalAmount().add(shoppingCartList.getFreight()));
            // 设置运费
            orderDetails.setTotalPostage(shoppingCartList.getFreight());
        }
    }

    /**
     * 最终化订单，插入数据库
     */
    private void finalizeOrder(DanmoShoppingOrderDetails orderDetails, DanmoShoppingCartOrdersDto ordersDto, LoginUser loginUser) {
        // 设置用户 ID
        orderDetails.setUserId(loginUser.getUserid());
        // 订单状态设置为 1（待付款等）
        orderDetails.setOrderStatus(1L);
        // 设置订单时间为当前时间
        orderDetails.setOrderTime(DateUtils.getNowDate());
        // 设置地址 ID
        orderDetails.setAddressesId(ordersDto.getDanmoAddresses().getId());

        // 插入订单详情
        danmoShoppingOrderDetailsMapper.insertDanmoShoppingOrderDetails(orderDetails);

        // 创建市场订单并插入
        DanmoMarketOrder marketOrder = new DanmoMarketOrder();
        // 复制属性
        BeanUtils.copyProperties(orderDetails, marketOrder);
        // 插入市场订单
        danmoMarketOrderMapper.insertDanmoMarketOrder(marketOrder);
    }


    // 生成订单ID的方法
    private Long generateOrderId() {
        Random random = new Random();
        return Math.abs(random.nextLong()); // 确保生成的ID是正数
    }


    /**
     * 生成加密手机号
     *
     * @param originalString
     * @return
     */
    private String generateOrderNumber(String originalString) {
        // 使用 StringBuilder 构造新的字符串
        StringBuilder maskedString = new StringBuilder(originalString);

        // 将第四到第七位的字符替换为 ****
        maskedString.replace(3, 7, "****");

        return String.valueOf(maskedString);
    }

    /**
     * 发货
     * @param danmoShoppingOrdersReq
     * @return
     */
    @Override
    public Result updateDanmoShoppingDelivery(DanmoShoppingOrdersReq danmoShoppingOrdersReq) {
        Long orderId = danmoShoppingOrdersReq.getOrderId();

        DanmoShoppingOrderDetails danmoShoppingOrderDetails = danmoShoppingOrderDetailsMapper.selectDanmoShoppingOrderDetailsById(orderId);
        if (danmoShoppingOrderDetails == null) {
            return Result.error("订单详情未找到");
        }

        DanmoMarketOrder danmoMarketOrder = danmoMarketOrderMapper.selectSingleOrder(orderId);
        if (danmoMarketOrder == null) {
            return Result.error("市场订单未找到");
        }

        if (danmoShoppingOrderDetails.getOrderStatus() != 2 || danmoMarketOrder.getOrderStatus() != OrderStatus.TO_BE_SHIPPED) {
            return Result.error("订单状态异常，请重试");
        }

        // 更新支付信息
        updateMarketOrderDelivery(danmoMarketOrder,danmoShoppingOrdersReq);
        updateOrderDetailsDelivery(danmoShoppingOrderDetails,danmoShoppingOrdersReq);

        // 保存更新
        danmoShoppingOrderDetailsMapper.updateDanmoShoppingOrderDetails(danmoShoppingOrderDetails);
        danmoMarketOrderMapper.updateDanmoMarketOrder(danmoMarketOrder);

        return Result.success(1, "支付成功");
    }

    @Override
    public Result updateDanmoShoppingReceiving(DanmoShoppingOrdersReq danmoShoppingOrdersReq) {
        Long orderId = danmoShoppingOrdersReq.getOrderId();

        DanmoShoppingOrderDetails danmoShoppingOrderDetails = danmoShoppingOrderDetailsMapper.selectDanmoShoppingOrderDetailsById(orderId);
        if (danmoShoppingOrderDetails == null) {
            return Result.error("订单详情未找到");
        }

        DanmoMarketOrder danmoMarketOrder = danmoMarketOrderMapper.selectSingleOrder(orderId);
        if (danmoMarketOrder == null) {
            return Result.error("市场订单未找到");
        }

        if (danmoShoppingOrderDetails.getOrderStatus() != 3 || danmoMarketOrder.getOrderStatus() != OrderStatus.TO_BE_RECEIVED) {
            return Result.error("订单状态异常，请联系平台");
        }

        // 更新支付信息
        updateMarketOrderReceiving(danmoMarketOrder);
        updateOrderDetailsReceiving(danmoShoppingOrderDetails);

        // 保存更新
        danmoShoppingOrderDetailsMapper.updateDanmoShoppingOrderDetails(danmoShoppingOrderDetails);
        danmoMarketOrderMapper.updateDanmoMarketOrder(danmoMarketOrder);

        return Result.success(1, "收货成功");
    }

    /**
     * 售后
     * @param danmoShoppingOrdersReq
     * @return
     */
    @Override
    public Result updateDanmoShoppingAfterSales(DanmoShoppingOrdersReq danmoShoppingOrdersReq) {
        return null;
    }

    /**
     * 新增物流订单号
     * @param danmoShoppingOrdersReq
     * @return
     */
    @Override
    public Result updateDanmoShoppingLogisticsOrderNumber(DanmoShoppingOrdersReq danmoShoppingOrdersReq) {
        Long orderId = danmoShoppingOrdersReq.getOrderId();

        DanmoShoppingOrderDetails danmoShoppingOrderDetails = danmoShoppingOrderDetailsMapper.selectDanmoShoppingOrderDetailsById(orderId);
        if (danmoShoppingOrderDetails == null) {
            return Result.error("订单详情未找到");
        }

        DanmoMarketOrder danmoMarketOrder = danmoMarketOrderMapper.selectSingleOrder(orderId);
        if (danmoMarketOrder == null) {
            return Result.error("市场订单未找到");
        }

        if (danmoShoppingOrderDetails.getOrderStatus() != 2 || danmoMarketOrder.getOrderStatus() != OrderStatus.TO_BE_SHIPPED) {
            return Result.error("订单状态异常，请联系平台");
        }

        String expressDeliveryNumber = danmoShoppingOrdersReq.getExpressDeliveryNumber();

        // 更新支付信息
        updateMarketLogisticsOrderNumber(danmoMarketOrder, Long.valueOf(expressDeliveryNumber));
        updateOrderLogisticsOrderNumber(danmoShoppingOrderDetails,expressDeliveryNumber);

        // 保存更新
        danmoShoppingOrderDetailsMapper.updateDanmoShoppingOrderDetails(danmoShoppingOrderDetails);
        danmoMarketOrderMapper.updateDanmoMarketOrder(danmoMarketOrder);

        return Result.success(1, "添加成功");
    }

    /**
     * 订单详情对象(物流)
     * @param danmoShoppingOrderDetails
     */

    private void updateOrderLogisticsOrderNumber(DanmoShoppingOrderDetails danmoShoppingOrderDetails,String expressDeliveryNumber) {
        danmoShoppingOrderDetails.setExpressDeliveryNumber(expressDeliveryNumber);
        danmoShoppingOrderDetails.setOrderStatus(3L);
        danmoShoppingOrderDetails.setDeliveryTime(DateUtils.getNowDate());
    }

    /**
     * 订单详情对象(物流)
     * @param danmoMarketOrder
     */
    private void updateMarketLogisticsOrderNumber(DanmoMarketOrder danmoMarketOrder,Long expressDeliveryNumber) {
        danmoMarketOrder.setExpressDeliveryNumber(expressDeliveryNumber);
        danmoMarketOrder.setOrderStatus(OrderStatus.TO_BE_RECEIVED);
        danmoMarketOrder.setDeliveryTime(DateUtils.getNowDate());
    }

    /**
     * 订单详情对象(收获)
     * @param danmoShoppingOrderDetails
     */
    private void updateOrderDetailsReceiving(DanmoShoppingOrderDetails danmoShoppingOrderDetails) {
        danmoShoppingOrderDetails.setOrderStatus(4L);
        danmoShoppingOrderDetails.setTransactionTime(DateUtils.getNowDate());
    }

    /**
     * 用户订单对象(收货)
     * @param danmoMarketOrder
     */
    private void updateMarketOrderReceiving(DanmoMarketOrder danmoMarketOrder) {
        danmoMarketOrder.setOrderStatus(OrderStatus.TO_BE_EVALUATED);
        danmoMarketOrder.setTransactionTime(DateUtils.getNowDate());
    }

    /**
     * 用户订单对象(快递)
     * @param danmoMarketOrder
     * @param danmoShoppingOrdersReq
     */
    private void updateMarketOrderDelivery(DanmoMarketOrder danmoMarketOrder,DanmoShoppingOrdersReq danmoShoppingOrdersReq) {
        danmoMarketOrder.setDeliveryTime(DateUtils.getNowDate());
        danmoMarketOrder.setOrderStatus(OrderStatus.TO_BE_RECEIVED);
        danmoMarketOrder.setPosExpress(danmoShoppingOrdersReq.getPosExpress());
        danmoMarketOrder.setExpressDeliveryNumber(Long.valueOf(danmoShoppingOrdersReq.getExpressDeliveryNumber()));
    }

    /**
     * 订单详情对象(快递)
     * @param danmoShoppingOrderDetails
     * @param danmoShoppingOrdersReq
     */
    private void updateOrderDetailsDelivery(DanmoShoppingOrderDetails danmoShoppingOrderDetails,DanmoShoppingOrdersReq danmoShoppingOrdersReq) {
        danmoShoppingOrderDetails.setDeliveryTime(DateUtils.getNowDate());
        danmoShoppingOrderDetails.setOrderStatus(3L);
        danmoShoppingOrderDetails.setPosExpress(danmoShoppingOrdersReq.getPosExpress());
        danmoShoppingOrderDetails.setExpressDeliveryNumber(danmoShoppingOrdersReq.getExpressDeliveryNumber());
    }
}
